package com.qidian.by.free.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.qidian.by.free.dto.ItemInfoDTO;
import com.qidian.by.free.service.FreeTemplateService;
import com.qidian.by.pojo.goods.entity.Item;
import com.qidian.by.util.pojo.EsResult;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.freemarker.FreeMarkerAutoConfiguration;
import org.springframework.boot.autoconfigure.web.WebProperties;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.*;

/**
 * @Author: CoolPro
 * @Description:
 * @Time: 2024-05-16 19:25
 **/
@Service
public class FreeTemplateServiceImpl implements FreeTemplateService {
    @Resource
    private FreeMarkerConfigurer freeMarkerConfigurer;

    @Resource
    private Properties freeTemplateProperties;

    @Override
    public EsResult<Map<String, String>> makeTemplate(String data) throws IOException, TemplateException {
        String templatePath = freeTemplateProperties.getProperty("template_loader_path");
        String outputPath = freeTemplateProperties.getProperty("output_path");
//      检查这个文件夹里是否有对应的商品文件
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        Template template = configuration.getTemplate(templatePath);
        LinkedHashMap<String, Object> item = EsResult.json2object(data, LinkedHashMap.class);
        LinkedHashMap itemData;
        String pageName;
        itemData = EsResult.json2object(item.get("data").toString(), LinkedHashMap.class);
        pageName = ((JSONObject) itemData.get("item")).get("itemId") + ".html";
        File outputFile = new File(outputPath + "/" + pageName);
        Map<String, String> reqData = new HashMap<>();
        reqData.put("path", outputPath);
        reqData.put("fileName", pageName);
        if (!outputFile.exists()) {
            FileWriter fileWriter = new FileWriter(outputPath + "/" + pageName);
            Map res = new HashMap();
            res.put("data", itemData);
            template.process(res, fileWriter);
            return EsResult.ok("生成成功", reqData);
        }
        return EsResult.ok("生成成功", reqData);
    }
}
